import fs from 'node:fs'
import path from 'node:path'
import Link from 'next/link'

const { pathname: currentDir } = new URL(import.meta.url)
const appDir = path.resolve(currentDir, '../../')

function getDemoRoot() {
  return path.dirname(currentDir)
}

// 获取示例组件文件列表
// 没有什么效率要求，所以就不加缓存了。
function getDemoRoutes(root?: string) {
  const rootDir = root ?? getDemoRoot()
  const fileOrDirs = fs.readdirSync(rootDir)

  const result: { name: string; path: string }[] = []

  fileOrDirs
    .map((i) => path.resolve(rootDir, i)) // 转换成绝对路径
    .filter((fileOrDir) => fs.lstatSync(fileOrDir).isDirectory())
    .map((dirPath) => {
      // 这里写死拉倒了，暂时不支持Markdown啥的
      const expectedFile = path.resolve(dirPath, 'page.tsx')
      if (fs.existsSync(expectedFile)) {
        const urlPath = path.relative(appDir, dirPath)
        const name = urlPath.split(path.sep).splice(1).join(path.sep)
        result.push({ name, path: urlPath })
      }

      const subRst = getDemoRoutes(dirPath)
      result.push(...subRst)
    })

  return result
}

export default function DemoList() {
  const routes = getDemoRoutes()

  return (
    <div>
      <h1 className="text-xl font-bold ">示例组件列表</h1>
      <ul>
        {routes.map((route) => (
          <li key={route.path} className="mt-2.5">
            <Link href={route.path}> {route.name} </Link>
          </li>
        ))}
      </ul>
    </div>
  )
}
